<template>
  <a-modal v-model:visible="visible" :title="modalTitle" width="35%" @ok="handleOk" @cancel="handleCancel">
    <a-form :model="formState" ref="formRef" :label-col="{ span: 5 }">
      <a-form-item label="用户" name="user_id" :rules="[{ required: true, message: '请选择用户' }]">
        <a-select v-model:value="formState.user_id" show-search
          :getPopupContainer="(triggerNode) => triggerNode.parentNode" placeholder="请选择用户" allowClear
          :filterOption="filterOption">
          <a-select-option v-for="(item, index) in state.options" :value="item.user_id" :label="item.name" :key="index"
            :disabled="item.is_admin_account == 0">{{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup>
import { ref, reactive } from "vue";
import { message } from "ant-design-vue";
import { bindBdContact } from "@/api/admin/storeUser";
import { all as getAll } from "@/api/contact";
import useModal from "@/utils/useModal";

const emits = defineEmits(["modal-success"]);
const formRef = ref();
const { visible, modalTitle } = useModal();
const state = reactive({
  options: [],
});

const formState = reactive({
  user_id: null,
  store_user_id: null,
  type: 1,
});

const show = (model) => {
  modalTitle.value = "绑定客服";
  Object.keys(model).forEach((key) => {
    formState[key] = model[key];
  });
  getAllList();
  visible.value = true;
};
//下拉框搜索
const filterOption = (input, option) => {
  //select有label这个字段
  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};
const getAllList = () => {
  getAll().then((res) => {
    if (res.code == 0) {
      const data = res.data;
      state.options = data;
    }
  });
};
const handleOk = async () => {
  await formRef.value.validate().then(() => {
    const params = {
      user_id: formState.user_id,
      store_user_id: formState.store_user_id,
      type: 1,
    };
    // 绑定
    bindBdContact({
      ...params,
    }).then((res) => {
      if (res.code == 0) {
        message.success(res.msg);
        formRef.value.resetFields();
        visible.value = false;
        emits("modal-success");
      }
    });
  });
};
const handleCancel = (e) => {
  formRef.value.resetFields();
};
// 暴露方法
defineExpose({
  show,
});
</script>
<style scoped></style>
